import React, { useRef, useState } from "react";
import type { FC } from "react";
import "./index.module.scss";
import { Table, Tag, Button } from "antd";
import type { TableProps } from "antd";
import { useOutletContext } from "react-router-dom";
interface DataItem {
  _id: string;
  title: string;
  isPublished: boolean;
  isStar: boolean;
  answerCount: number;
  createdAt: string;
  isDeleted: boolean;
}
interface SelectedRowKeysRef {
  selectedRows: DataItem[];
  selectedRowKeys: React.Key[];
}
const columns: TableProps<DataItem>["columns"] = [
  {
    title: "标题",
    dataIndex: "title",
    key: "title",
    align: "center",
  },
  {
    title: "是否发布",
    dataIndex: "isPublished",
    key: "isPublished",
    align: "center",

    render: (_, { isPublished }) => (
      <>
        <Tag color={isPublished ? "blue" : ""}>
          {isPublished ? "已发布" : "未发布"}
        </Tag>
      </>
    ),
  },

  {
    title: "答卷",
    key: "answerCount",
    dataIndex: "answerCount",
    align: "center",
  },
  {
    title: "创建时间",
    key: "createdAt",
    dataIndex: "createdAt",
    align: "center",
  },
];
const initialState = {
  filteredDataList: [] as DataItem[],
  originalDataList: [] as DataItem[],
};

const reducer = (
  state: typeof initialState,
  action: { type: string; payload?: DataItem[]; keys?: React.Key[] }
) => {
  switch (action.type) {
    case "FILTER_DATA":
      return {
        ...state,
        filteredDataList:
          action.payload?.filter((item) => item.isDeleted) || [],
        originalDataList: action.payload || [],
      };
    case "ADD_SELECTED_ROWS":
      return {
        ...state,
        filteredDataList: state.filteredDataList.filter((item) => {
          return !action.keys?.includes(item._id);
        }),
        // action.payload中的id=action.keys 的id,id的对象中的item.isDeleted = false;
        originalDataList: state.originalDataList.map((item) => {
          if (action.keys?.includes(item._id)) {
            item.isDeleted = false;
          }
          return item;
        }),
      };
    case "REMOVE_SELECTED_ROWS":
      return {
        ...state,
        filteredDataList: state.filteredDataList.filter(
          (item) => !action.keys?.includes(item._id)
        ),
        originalDataList: state.originalDataList.filter((item) => {
          if (!action.keys?.includes(item._id)) {
            return item;
          }
          console.log(item, 111);
        }),
      };
    default:
      return state;
  }
};

const Trash: FC = () => {
  const selectedRowKeysRef = useRef<SelectedRowKeysRef>({
    selectedRows: [],
    selectedRowKeys: [],
  });
  const { dataList } = useOutletContext<{ dataList: DataItem[] }>();
  const [state, dispatch] = React.useReducer<typeof reducer>(
    reducer,
    initialState
  );

  React.useEffect(() => {
    dispatch({ type: "FILTER_DATA", payload: dataList });
  }, [dataList]);
  const trashControls = (type: number) => {
    if (type === 1) {
      dispatch({
        type: "ADD_SELECTED_ROWS",
        keys: selectedRowKeysRef.current.selectedRowKeys,
      });
    } else if (type === 2) {
      dispatch({
        type: "REMOVE_SELECTED_ROWS",
        keys: selectedRowKeysRef.current.selectedRowKeys,
      });
    }
    //TODO reducer中的state.originalDataList是list的最新值,可以进行redux中存储值的dataList的更新
  };
  // React.useEffect(() => {
  //   console.log(state.originalDataList, "dataList");
  // }, [state.originalDataList]); // 监听 state.originalDataList 的变化

  return (
    <div className="Trash">
      <div>
        <Button
          type="primary"
          style={{ margin: "0 10px 5px 0" }}
          onClick={() => {
            trashControls(1);
          }}
        >
          恢复
        </Button>
        <Button
          color="danger"
          variant="outlined"
          onClick={() => {
            trashControls(2);
          }}
        >
          删除
        </Button>
      </div>
      <Table<DataItem>
        columns={columns}
        dataSource={state.filteredDataList}
        pagination={false}
        scroll={{ y: 55 * 5 }}
        rowKey={"_id"}
        rowSelection={{
          type: "checkbox",
          columnWidth: "64px",
          onChange: (selectedRowKeys, selectedRows) => {
            selectedRowKeysRef.current.selectedRowKeys = selectedRowKeys;
            selectedRowKeysRef.current.selectedRows = selectedRows;
            console.log(
              `selectedRowKeys: ${selectedRowKeys}`,
              "selectedRows: ",
              selectedRows
            );
          },
        }}
      />
    </div>
  );
};

export default Trash;
